<script setup>
	import { nextTick, ref } from 'vue'
	import SimpleQuery from './simpleQuery.vue'
	import IndexFun from './customQuery/index.vue'
	import { message } from 'ant-design-vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import { useSimpleQueryStore } from '@/views/plugin/dashboard/store/simpleQuery'
	import { useCustomQueryStore } from '@/views/plugin/dashboard/store/customQuery'

	const simpleQueryStore = useSimpleQueryStore()
	const customQueryStore = useCustomQueryStore()
	const simpleQueryRef = ref()
	const customQueryRefCom = ref()
	const currentType = ref('query')
	const formData = ref({})
	const emit = defineEmits(['loadData'])
	// 打开抽屉
	const onOpen = (record) => {
		if (record) {
			currentType.value = record.type || 'query'
			nextTick(() => {
				if (currentType.value === 'query') {
					formData.value = {
						...{
							id: '',
							dataConnectorId: '',
							type: 'query',
							itemConfig: {
								// 驼峰转换状态
								enableCamelCase: false,
								// 选中的列
								selectedColumns: [],
								// 格式化配置
								formatConfig: [],
								// 表格列定义
								columns: [],
								// 表名
								tableName: '',
								// 查询条件
								conditions: [],
								// 排序
								sorts: []
							}
						},
						...record
					}
					simpleQueryRef.value?.onOpen(formData.value)
				} else {
					formData.value.id = record.id
					console.log(record.id, 'record.id')
					customQueryRefCom.value?.onOpen(record)
				}
			})
		}
	}

	// 获取配置
	const getConfig = async () => {
		if (currentType.value === 'query') {
			return await simpleQueryRef.value?.getConfig()
		} else {
			return await customQueryRefCom.value?.getConfig()
		}
	}

	// 关闭方法
	const onClose = () => {
		// 清空数据
		formData.value = {}
	}

	// 保存数据集配置
	const onSave = async () => {
		try {
			// 根据当前类型获取对应的store数据
			let config, itemConfig
			if (currentType.value === 'query') {
				config = simpleQueryStore.formData
				if (!config) {
					message.error('请完善数据集配置')
					return
				}
				itemConfig = config.itemConfig
			} else {
				config = customQueryStore.formData
				if (!config) {
					message.error('请完善数据集配置')
					return
				}
				// 自定义查询的配置结构与简单查询不同，需要适配
				itemConfig = config.config
			}

			const params = {
				id: formData.value.id,
				datasetId: config.datasetId,
				itemConfig: itemConfig,
				type: currentType.value,
				customItemConfig: currentType.value !== 'query' ? config.config : undefined
			}
			await datasetApi.saveItemConfig(params)
			emit('loadData')
			onClose()
		} catch (error) {
			console.log(error)
		}
	}
	defineExpose({
		onOpen,
		getConfig
	})
</script>

<template>
	<div class="bg-white">
		<SimpleQuery v-if="currentType === 'query'" ref="simpleQueryRef" @loadData="emit('loadData')" @onSave="onSave" />
		<index-fun v-else ref="customQueryRefCom" @loadData="emit('loadData')" @onSave="onSave" />
	</div>
</template>
